#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<stdlib.h>
#include<regex.h>
#define SUBSLEN 10
#define EBUFLEN 128
#define BUFLEN 1024

int main(int argc, char *argv[])
{
  FILE *fp;
  size_t len;
  regex_t re;
  regmatch_t subs[SUBSLEN];
  char matched[BUFLEN];
  char errbuf[EBUFLEN];
  int err,i;

  char string[] = "AAAAAabaaababAbAbCd12312312311(123){12}";
  char pattern[] = "(\\([0-9]+\\))(\\{[0-9]+\\}{1})$";

  printf("String: %s\n",string);
  printf("Pattern: \"%s\"\n",pattern);

  err = regcomp(&re,pattern,1);//REG_EXTENDED);

  if(err)
    {
      len = regerror(err,&re,errbuf,sizeof(errbuf));
      fprintf(stderr,"error: regcomp: %s\n",errbuf);
      exit(1);
    }
  printf("Total has subexpression: %d\n",re.re_nsub);
  err = regexec(&re,string,(size_t)SUBSLEN,subs,0);

  if(err == REG_NOMATCH)
    {
      fprintf(stderr,"Sorry,no match...\n");
      regfree(&re);
      exit(0);
    }
  else if(err)
    {
      len = regerror(err,&re,errbuf,sizeof(errbuf));
      fprintf(stderr,"error: regexec: %s\n",errbuf);
      exit(1);
    }

  for(i = 0;i <= re.re_nsub;i++)
    {
      if(i == 0)
        {
          printf("begin: %d,end: %d, ",subs[i].rm_so,subs[i].rm_eo);
        }
      else
        {
          printf("subexpression %d begin: %d, end: %d, ",
                 i,subs[i].rm_so,subs[i].rm_eo);
        }
      len = subs[i].rm_eo - subs[i].rm_so;
      memcpy(matched,string + subs[i].rm_so,len);
      matched[len] = '\0';
      printf("match: %s\n",matched);
    }
  regfree(&re);
  exit(0);
  return 0;
}
